import _ from "lodash";
import BW from "./bwCommon";
import urls from "./apiUrls";
import axios from "axios";
import qs from "qs";
import { Loading } from "element-ui";

/**
 * [request Ajax 公共库]
 * @param  {[String]} apiName   [api 缩写名]
 * @param  {[Object]} paramsObj [Post 参数]
 * @param  {[Object]} sc [请求cancelToken对象]
 */
const splRequest = function(apiName, paramsObj, sc) {
  if (_.isUndefined(urls[apiName])) {
    BW.Toast("接口地址未注册");
    return;
  }
  let sign = wVue.$store.getters.getUsrInfo ? wVue.$store.getters.getUsrInfo.Sign : ''
  let options = {
    method: "post",
    url: urls[apiName],
    data: paramsObj? Object.assign(paramsObj, {sign: sign}): {sign: sign},
    transformRequest: [
      function(data) {
        // 转换成表单数据格式
        data = qs.stringify(data);
        return data;
      }
    ],
    responseType: "json",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  }
  if (typeof (sc) !== 'undefined') options.cancelToken = sc.source.token
  return new Promise((resolve, reject) => {
    axios(options).then(res => {
      if (typeof (sc) !== 'undefined') sc.source = null
      if (!res) {
        reject({
          rspInf: "服务器 data 数据出错！"
        });
      }
      if (res.data) {
        if (res.data.Status === 200) {
          resolve(res.data);
        } else {
          if (res.data.Status === 400) {
            BW.Toast("登录失效，请重新登录");
            return;
          }
          BW.Toast(res.data.Msg || "错误提示数据异常！");
          reject(res.data.Msg);
        }
      }
    }).catch(error => {
      if (typeof (sc) !== 'undefined') sc.source = null
      if (error.response) {
        BW.Toast("服务器出问题了！");
        reject(error.response);
      } else {
        BW.Toast((error && error.rspInf) || "服务器出问题了！");
        reject(error);
      }
    });
  });
};

export default splRequest;
